package com.tao.picture.base.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.tao.picture.ui.person.data.entity.Person
import com.tao.picture.ui.person.data.local.ImageDao

/**
 * 实体可以是多个
 * version可以升级
 */
@Database(entities = [Person::class], version = 2, exportSchema = false)
abstract class ImageDatabase : RoomDatabase() {
    // 多个需要创建多个dao
    abstract val imageDao: ImageDao

    companion object {
        @Volatile
        private var instance: ImageDatabase? = null

        // 单例
        fun getDatabase(context: Context): ImageDatabase =
            instance ?: synchronized(this) {
                instance ?: getInstance(context).also {
                    instance = it
                }
            }

        // 创建database
        private fun getInstance(appContext: Context) =
            // 数据库名
            Room.databaseBuilder(appContext, ImageDatabase::class.java, "person_database")
//                .fallbackToDestructiveMigration() // 清空数据并更新，不建议
                .addMigrations(MIGRATION_1_2)
                .build()

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 执行sql 此示例便是增加一列‘url’默认值为空
                // "CREATE TABLE `remote_keys` (`tId` TEXT NOT NULL, `prevKey` INTEGER, `nextKey` INTEGER, PRIMARY KEY(`tId`))"
                database.execSQL("ALTER TABLE person ADD COLUMN url TEXT NOT NULL DEFAULT ''")
            }
        }
    }
}